<template>
    <div class="live" id="index">
        <div class="live-top">
            <div class="live-title">{{StudioName}}</div>
            <div class="login-contain">
                <div class="login-user" v-if="logined">当前登录:{{loginedUser}}
                    <button @click="exit">退出</button>
                </div>
                <button @click="showLoginDialog" v-else>登录</button>
            </div>
        </div>
       <!--  <div class="free-tips" v-if="live && !logined">免费观看时长：{{'0' + freeTime.minute}}:{{freeTime.second<10?( '0' + freeTime.second): freeTime.second}}</div> -->
        <div class="live-box-contain">
            <video :src="liveSrc" class="video-native" height="100%" width="100%" v-if="showVideo" preload="auto" webkit-playsinline="true" playsinline="" x5-playsinline="true" x-webkit-airplay="true" controls="controls"></video>
            <p v-else>请登录之后观看</p>
        </div>
        <ul class="c-list" ref="componentScrollBar">
            <li v-for="(item, index) in messageLists" :key="index">
                <span class="msg-time">{{formatMsgDate(item.createTime)}}</span>
                <span :class="['level', item.admin?formatAdmin(item.name):formatLevel(item.level)]">{{item.admin? '' : (item.level || '普通')}}</span>
                <span :class="['nickname',item.admin?'u-t':'']">{{item.admin ? (item.name == '主播老师' ? teacher : '直播助理' ) : item.name}}:</span>
                <span :class="['chat-msg-item',item.admin ? 'u-t-b' : '']" v-html="formatChatText(item.content)"></span>
            </li>
        </ul>
        <div class="chat-feat">
            <div class="emoji-wrap" v-show="showEmoji">
                <img v-for="(item,index) in emoji" :key="index" :src="'/static/qqFace/'+index+'.gif'" :alt="item" width="24" height="24" @click="addEmoji2Chat('['+item+']')" :title="item">
            </div>
            <i class="smile-o" @click="showEmoji=!showEmoji"></i>
            <textarea class="cs-textarea" v-model.trim="msg" name="" maxlength="40" placeholder="这里输入聊天内容" ref="textarea" @keyup.enter="sendMsg"></textarea>
            <div class="b-btn" @click="sendMsg">发送</div>
        </div>
        <div class="dialog-modal" v-if="needLogin">
            <div class="login-dialog">
                <template v-if="nickDialog">
                    <div class="login-dialog-title">设置昵称</div>
                    <div class="login-form">
                        <div class="login-dialog-input-item">
                            <label for="nickname">昵称</label>
                            <input id="nickname" type="text" placeholder="请输入昵称" v-model="nickName">
                        </div>
                        <div class="login-dialog-btn">
                            <button class="login-btn" @click="setName">立即登录</button>
                        </div>
                    </div>
                </template>
                <template v-else>
                    <div class="login-dialog-title">登录</div>
                    <div class="login-form">
                        <div class="login-dialog-input-item">
                            <label for="photo">手机号码</label>
                            <input id="photo" type="text" placeholder="请输入手机号码" v-model="username">
                        </div>
                        <div class="login-dialog-input-item">
                            <label for="num">邀请码</label>
                            <input id="num" type="text" placeholder="请输入邀请码" v-model="code">
                        </div>
                        <div class="login-dialog-btn">
                            <button class="login-btn" @click="getLogin">立即登录</button>
                        </div>
                        <div class="login-dialog-btn">
                            <button class="cancel-btn" @click="cancelLogin">取消</button>
                        </div>
                    </div>
                </template>
            </div>
        </div>
    </div>
</template>
<script>
import {
    getConfig,
    postSMS,
    getMessages,
    postMessage,
    loginByUserCode,
    setNickName
} from '@/api/api'
import videojs from 'video.js'
window.videojs = videojs
// require('videojs-flash/dist/videojs-flash')
require('videojs-contrib-hls/dist/videojs-contrib-hls')
import 'video.js/dist/video-js.css'
import 'vue-video-player/src/custom-theme.css'
import { videoPlayer } from 'vue-video-player'
import emoji from '@/assets/js/emoji.js'
export default {
    data() {
        return {
            playerOptions: {
                height: '100%',
                overNative: false,
                sourceOrder: true,
                techOrder: ['html5', 'flash'], // 兼容顺序
                sources: null,
                controlBar: { //控制栏
                    timeDivider: false, // 时间分割线
                    remainingTimeDisplay: false, //显示剩余时间
                    progressControl: false, //进度条
                    durationDisplay: false //总时间
                },
                flash: {
                    hls: { withCredentials: false },
                    swf: '/static/media/VideoJS.swf' //使用自己的flash播放器
                },
                html5: { hls: { withCredentials: false } },
                //poster: "/static/poster.jpg", //默认封面
            },
            liveSrc: '',
            messageLists: [],
            username: '',
            code: '',
            nickName: '',
            logined: false,
            msg: '',
            loginedUser: '',
            emoji: emoji,
            showEmoji: false,
            componentScrollBar: null,
            freeTime: {
                minute: 4,
                second: 60
            },
            freeTimer: null,
            live: false,
            freeTips: '请联系客服17898829204（同微信）获取观看账号',
            StudioName: '红色K线',
            timer: null,
            showVideo: false,
            needLogin: false,
            nickDialog: false,
            username: '',
            code: '',
            nickName: ''
        }
    },
    components: {
        videoPlayer
    },
    sockets: {
        connect: function() {
            console.log('聊天服务器连接成功')
            console.log(this.APPID)
            this.$socket.emit('bind', this.APPID)
        },
        binded: function() {
            console.log('APPID bind 成功,开始登录socket服务器')
            var token = localStorage.getItem('token');
            if (token) {
                this.$socket.emit('login', token)
            }
        },
        connect_error: function(e) {
            console.log('聊天服务器连接出错，错误信息:' + e)
        },
        reconnect: function() {
            console.log('聊天服务器重连')
        },
        reconnect_failed: function() {
            console.log('聊天服务器重连失败')
        },
        send_fail: function(msg) {
            console.log('消息发送失败,错误提示:' + msg)
        },
        config_update: function(status) {
            if (status.live) {
                var s = JSON.parse(status.live)
                if (s) {
                    console.log('直播开启')
                    this.live = true;
                    this.liveSrc = 'http://live.sczzyf.com/live/live.m3u8'
                    this.playerOptions.sources = [{
                        withCredentials: false,
                        type: "application/x-mpegURL",
                        src: "http://live.sczzyf.com/live/live.m3u8"
                    }]
                } else {
                    console.log('直播关闭')
                    this.live = false;
                    this.playerOptions.loop = true;
                    this.playerOptions.controlBar.progressControl = true;
                    this.liveSrc = this.videosUrl
                    this.playerOptions.sources = [{
                        type: "video/mp4",
                        src: this.videosUrl
                    }]
                }
            }
        },
        logined: function(val) {
            if (val == '0') {
                console.log('聊天服务器登录失败')
                alert('聊天服务器登录失败，请重新登录!')
            } else {
                console.log('聊天服务器登录成功')
            }
        },
        message: function(val) {
            console.log('收到消息:', val)
            this.messageLists.push(val)
            this.$nextTick(() => {
                this.componentScrollBox.scrollTop = this.componentScrollBox.scrollHeight;
            })
        }
    },
    created: function() {
        var loginTime = localStorage.getItem('loginTime') || 0;
        var now = new Date().getTime()
        if (now - loginTime > 604800000) {
            localStorage.clear()
        }
        var token = localStorage.getItem('token');
        var userObj = localStorage.getItem('user') || '{}';
        var user = JSON.parse(userObj);
        if (token && user.name) {
            this.logined = true;
            this.loginedUser = user.name;
            this.showVideo = true;
        }

        this.getMessageList()
        this.timer = setInterval(() => {
            this.$socket.emit('add_time', 2)
        }, 2 * 60000)
    },
    mounted: function() {
        var _this = this;
        document.addEventListener('click', function(e) {
            var event = e || window.event;
            var target = event.target || event.srcElement;
            if (_this.showEmoji && target.className != 'smile-o') {
                _this.showEmoji = false;
            }
        }, false)
        this.componentScrollBox = this.$refs.componentScrollBar;
        getConfig('live,videosUrl,StudioName,freeTips,StudioName').then(res => {
            this.StudioName = res.StudioName;
            document.title = res.StudioName;
            this.freeTips = res.freeTips;
            var live = JSON.parse(res.live);
            this.live = live;
            this.videosUrl = res.videosUrl

            if (!live) {
                this.playerOptions.loop = true;
                this.playerOptions.controlBar.progressControl = true;
                this.playerOptions.sources = [{
                    type: "video/mp4",
                    src: res.videosUrl
                }]
                this.liveSrc = res.videosUrl
            } else {

                this.liveSrc = 'http://live.sczzyf.com/live/live.m3u8'
                this.playerOptions.sources = [{
                    withCredentials: false,
                    type: "application/x-mpegURL",
                    src: "http://live.sczzyf.com/live/live.m3u8"
                }]
                // var token = localStorage.getItem('token');
                // if (!token) {
                //     var ft = localStorage.getItem('freeTime') || JSON.stringify(this.freeTime)
                //     var freeTime = JSON.parse(ft);
                //     var ftMin = freeTime.minute;
                //     var ftSec = freeTime.second;
                //     var _this = this;
                //     if (ftMin == 0 && ftSec == 0) {
                //         //提示登录
                //         this.freeTime = {
                //             minute: 0,
                //             second: 0
                //         }
                //         this.showVideo = false;
                //         this.needLogin = true;
                //         alert(this.freeTips)
                //         // _this.$router.push('/login')
                //         return;
                //     } else {
                //         this.freeTimer = setInterval(function() {
                //             if (ftSec > 0) {
                //                 ftSec -= 1;
                //             } else {
                //                 if (ftMin == 0) {
                //                     clearInterval(_this.freeTimer)
                //                     _this.freeTimer = null;
                //                     // _this.videoPause();
                //                     _this.showVideo = false;
                //                     _this.needLogin = true;
                //                     alert(_this.freeTips)
                //                     // _this.$router.push('/login')
                //                     return;
                //                 }
                //                 ftMin -= 1;
                //                 ftSec = 60;
                //             }

                //             _this.freeTime = {
                //                 minute: ftMin,
                //                 second: ftSec
                //             }

                //             localStorage.setItem('freeTime', JSON.stringify(_this.freeTime))
                //         }, 1000)
                //     }
                // }
            }
        })
    },
    methods: {
        getMessageList: function() {
            getMessages().then(res => {
                this.messageLists = res;
                this.$nextTick(() => {
                    this.componentScrollBox.scrollTop = this.componentScrollBox.scrollHeight;
                })
            })
        },
        formatMsgDate: function(time) {
            var date = new Date(time);
            var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
            var mins = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
            return hours + ':' + mins;
        },
        formatLevel: function(level) {
            switch (level) {
                case '黄金':
                    return 'lv2'
                case '白银':
                    return 'lv1'
                case '普通':
                    return 'lv0'
                default:
                    return 'lv0'
            }
        },
        formatAdmin: function(name) {
            if (name == '主播老师') {
                return 'lv-t'
            } else if (name == '直播助理') {
                return 'lv-s'
            }
        },
        formatChatText: function(text) {
            if (!text) {
                return text;
            }

            text = text.replace(/\[[\u4E00-\u9FA5]{1,3}\]/gi, function(word) {
                var newWord = word.replace(/\[|\]/gi, '');
                var index = emoji.indexOf(newWord);
                var imgHTML = '';
                if (index < 0) {
                    return word;
                }

                imgHTML = `<img width="24" height="24" style="vertical-align: middle;" title="${newWord}" src="/static/qqFace/${index}.gif" alt="${newWord}">`
                return imgHTML;
            });
            return text;
        },
        sendMsg: function() {
            if (!this.logined) {
                alert('请登录之后再发言');
                // this.$router.push('/login');
                this.needLogin = true;
                return;
            }
            if (!this.msg) {
                alert('请输入聊天内容');
                return;
            }
            var msg = {
                content: this.msg,
                name: this.loginedUser
            }
            this.$socket.emit('send', msg)
            console.log('发送的消息:', msg)
            this.msg = '';
        },
        addEmoji2Chat: function(name) {
            var textDom = this.$refs.textarea;
            var cursorPos = 0; //光标位置
            if (document.selection) {
                // IE Support
                var selectRange = document.selection.createRange();
                selectRange.moveStart('character', -this.msg.length);
                cursorPos = selectRange.text.length;
            } else if (textDom.selectionStart || textDom.selectionStart == '0') {
                // Firefox support
                cursorPos = textDom.selectionStart;
            }
            if (cursorPos != this.msg.length) {
                //光标位置不是在最后
                var msgArr = this.msg.split(''); //分隔成数组
                msgArr.splice(cursorPos, 0, name) //在光标位置插入emoji
                this.msg = msgArr.join(''); //转回字符串
            } else {
                this.msg += name;
            }
            this.showEmoji = false;
        },
        showLoginDialog: function() {
            // this.$router.push('/login')
            this.needLogin = true;
        },
        closeLoginDialog: function() {
            this.loginDialog = false;
        },
        exit: function() {
            localStorage.clear();
            alert('退出成功');
            this.$router.go(0)
        },
        getLogin: function() {
            if (!this.username) {
                alert('请输入账号');
                return;
            }
            if (!this.code) {
                alert('请输入邀请码');
                return;
            }
            var data = {
                username: this.username,
                code: this.code
            }
            loginByUserCode(data).then(res => {
                console.log(res)
                localStorage.setItem('token', res.token)
                localStorage.setItem('user', JSON.stringify(res.user))
                localStorage.setItem('loginTime', new Date().getTime())
                var freeTime = {
                    minute: 4,
                    second: 60
                }
                localStorage.setItem('freeTime', JSON.stringify(freeTime))
                if (!res.user.name) {
                    this.nickDialog = true;
                    return;
                } else {
                    localStorage.setItem('nickName', res.user.name)
                    alert('登录成功');
                    this.$socket.emit('login', res.token)
                    // this.$router.push('/')
                    this.logined = true;
                    this.showVideo = true;
                    this.loginedUser = res.user.name;
                    this.cancelLogin();
                }
                sessionStorage.setItem('s', 1)
                clearInterval(this.freeTimer)
                this.freeTimer = null;
            })
        },
        setName: function() {
            if (!this.nickName) {
                alert('请输入昵称');
                return;
            }
            setNickName(this.nickName).then(res => {
                localStorage.setItem('token', res.token)
                localStorage.setItem('nickName', this.nickName)
                alert('登录成功');
                this.$socket.emit('login', res.token)
                this.logined = true;
                this.loginedUser = this.nickName;
                this.cancelLogin();
            })
        },
        cancelLogin: function() {
            this.username = '';
            this.code = '';
            this.needLogin = false;
        }
    },
    destroyed: function() {
        clearInterval(this.freeTimer)
        this.freeTimer = null;
        clearInterval(this.timer)
        this.timer = null;
    }
}

</script>
<style scoped>
/*视频框*/

.live-box-contain {
    height: 40vh;
    position: relative;
}

.live-top {
    height: 30px;
    overflow: hidden;
    zoom: 1;
    background-color: #000;
}

.live-title {
    float: left;
    line-height: 30px;
    font-size: 18px;
    color: #fff;
    margin: 0 5px;
}

.login-contain {
    float: right;
}

.login-contain button {
    height: 20px;
    margin: 5px;
    background-color: #f75e5e;
    border: none;
    outline: none;
    color: #fff;
    border-radius: 3px;
}

.login-user {
    display: inline-block;
    color: #fff;
    height: 20px;
    line-height: 20px;
    margin: 0 5px;
}







/*消息列表*/

.c-list {
    height: calc(60vh - 80px);
    margin: 0;
    padding: 0;
    font-size: 14px;
    box-sizing: border-box;
    list-style: none;
    overflow-y: scroll;
    background-color: #766f99;
}

.c-list li {
    padding-left: 10px;
    padding-right: 10px;
    margin-bottom: 5px;
    line-height: 20px;
    color: #555;
}

.msg-time {
    color: #fff;
    padding-left: 8px;
    padding-right: 8px;
    vertical-align: middle;
    display: inline-block;
    background-color: #000;
    border-radius: 3px;
    margin: 0 5px;
    box-shadow: 2px 2px 2px #666;
}

.nickname {
    color: #fff;
    padding-left: 8px;
    padding-right: 8px;
    vertical-align: middle;
    display: inline-block;
    background-color: #2b6cb1;
    border-radius: 3px;
    box-shadow: 2px 2px 2px #666;
    margin-left: 5px;
    margin-right: 5px;
}

.chat-msg-item {
    display: inline-block;
    padding-left: 8px;
    padding-right: 8px;
    background-color: #fff;
    border-radius: 3px;
    word-break: break-all;
    word-wrap: break-word;
    box-shadow: 2px 2px 2px #666;
    color: #000;
    margin-top: 2.5px;
    margin-bottom: 2.5px;
}







/*会员等级*/

.level {
    display: inline-block;
    width: 46px;
    height: 16px;
    color: #fff;
    font-size: 12px;
    line-height: 16px;
    text-align: center;
    vertical-align: middle;
}

.lv0 {
    background: url(../assets/lv0.png) no-repeat center;
}

.lv1 {
    background: url(../assets/lv2.gif) no-repeat center;
}

.lv2 {
    background: url(../assets/level.gif) no-repeat center;
}

.lv-t {
    background: url(../assets/anchor.png) no-repeat center;
}

.lv-s {
    background: url(../assets/support.png) no-repeat center;
}







/*输入框*/

.chat-feat {
    height: 50px;
    /*overflow: hidden;*/
    position: relative;
    zoom: 1;
}







/*emoji*/

.emoji-wrap {
    padding: 5px;
    position: absolute;
    bottom: 30px;
    left: 0;
    border: 1px solid #bdbdbd;
    z-index: 99;
    background-color: #fff;
}

.smile-o {
    display: inline-block;
    width: 32px;
    height: 32px;
    background: url(../assets/smile.png) no-repeat center center;
    background-size: cover;
    margin: 5px;
    vertical-align: middle;
}

.emoji-wrap {
    position: absolute;
    bottom: 52px;
    left: 0;
    border: 1px solid #bdbdbd;
    z-index: 99;
    background-color: #fff;
}

.cs-textarea {
    vertical-align: middle;
    width: calc(100% - 130px);
    box-sizing: border-box;
    height: 45px;
    padding: 5px;
    border: 1px solid #ff921a;
    border-right: none;
    border-radius: 4px 0 0 4px;
    overflow: hidden;
    resize: none;
    outline: none;
    margin-right: -3px;
    margin-top: 2px;
}

.b-btn {
    display: inline-block;
    vertical-align: middle;
    width: 80px;
    height: 45px;
    line-height: 45px;
    background: #f70;
    color: #fff;
    text-align: center;
    cursor: pointer;
    border-radius: 0 4px 4px 0;
    margin-top: 2px;
    margin-left: -1px;
}


.free-tips {
    width: 100%;
   /* position: absolute;
    left: 0;
    top: 0;
    color: #ff0000;
    z-index: 9;*/
    /*margin-bottom: 20px;*/
}

.video-native {
    background-color: #000;
}





/*dialog*/

.dialog-modal {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
    z-index: 99999999;
    background-color: rgba(0, 0, 0, .9)
}

.login-dialog {
    width: 100%;
    position: fixed;
    top: 50%;
    transform: translateY(-50%);
}

.login-dialog-title {
    text-align: center;
    font-size: 20px;
    line-height: 20px;
    margin: 20px 0;
    color: #fff;
}

.login-form {
    padding: 5px 20px;
}

.login-dialog-input-item {
    margin: 10px 0;
}

.login-dialog-input-item label {
    display: inline-block;
    width: 80px;
    font-size: 18px;
    vertical-align: middle;
    text-align: justify;
    text-align-last: justify;
    color: #fff;
}

.login-dialog-input-item input {
    height: 30px;
    padding-left: 5px;
    margin-left: 5px;
    vertical-align: middle;
    border-radius: 5px;
    outline: none;
    border: 1px solid #fff;
}

.login-dialog-btn {
    padding: 0 20px;
    margin: 20px 0;
    height: 40px;
}

.login-dialog-btn button {
    width: 100%;
    height: 100%;
    border-radius: 5px;
    outline: none;
    border: none;
    font-size: 16px;
}

.login-btn {
    background-color: #fff;
    color: #000;
}

.cancel-btn {
    background-color: #ff0000;
    color: #fff;
}

</style>
